<?php

namespace App\Http\Requests\School;

use App\Models\BookRule;
use App\Models\BookRulePrice;
use App\Models\PriceCategory;
use App\Rules\ValidatePrice;
use Illuminate\Foundation\Http\FormRequest;

/**
 * Class EditBookRulePrice
 * @package App\Http\Requests\School
 */
class EditBookRulePrice extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'total_price' => [
                'required',
                new ValidatePrice()
            ],
            'rule_id' => [
                'required',
                function ($attribute, $value, $fail) {
                    $bookRule = BookRule::query()->where('school_id', \Auth::user()->school_id)->find($value);
                    // 判断此订餐规则状态
                    if ($bookRule->is_cancel === BookRule::CANCELED) {
                        return $fail('当前订餐规则已被取消，操作失败!');
                    }
                    // 订餐规则已结算不能操作条目
                    if ($bookRule->is_settled === BookRule::SETTLED) {
                        return $fail('当前订餐规则已结算，操作失败!');
                    }
                }
            ],
            'category_id' => [
                'required',
                function ($attribute, $value, $fail) {
                    // 若当前学校下的条目表中不存在状态为已启用的该条目
                    if (PriceCategory::where('school_id', \Auth::user()->school_id)->where('status', 1)->where('id', $value)->doesntExist()) {
                        return $fail('未找到已启用的该条目信息');
                    }
                    // 检验除当前编辑的条目外，是否已经添加过了此条目
                    if (BookRulePrice::where('rule_id', $this->rule_id)->where('category_id', $value)->where('id', '<>', $this->id)->exists()) {
                        return $fail('该条目已添加');
                    }
                }
            ]
        ];
    }

    /**
     * @return array
     */
    public function attributes()
    {
        return [
            'category_id' => '条目',
            'total_price' => '成本',
            'rule_id' => '订餐规则'
        ];
    }

    /**
     * @return array
     */
    public function messages()
    {
        return [
            'rule_id.required' => ':attribute不存在',
            'category_id.required' => '请选择:attribute',
            'total_price.required' => '请填写:attribute'
        ];
    }
}
